<template>
  <div class="audio-player">
    <div class="mini-player">
      <div class="icon">
        <i :class="playIcon" @click="togglePlay"></i>
      </div>
      <div class="control">
        <div class="text">
          <span class="time time-r">
            {{ format(currentTime) }}/{{ format(duration) }}</span
          >
        </div>
        <div class="progress">
          <van-slider v-model="currentTime" @change="percentChange" />
        </div>
      </div>
    </div>
    <audio :id="playerId" :src="source" @timeupdate="updateTime" />
  </div>
</template>

<script>
export default {
  name: "audio-player",
  data() {
    return {
      playerId:
        "aliplayer_" +
        Math.random()
          .toString(36)
          .substr(2),
      currentTime: 0,
      playing: false,
      instance: null
    };
  },
  props: {
    source: ,
    duration: 0,
    name: 
  },
  computed: {
    playIcon() {
      return this.playing
        ? "van-icon van-icon-pause-circle-o"
        : "van-icon van-icon-play-circle-o";
    }
  },
  mounted() {
    this.instance = document.querySelector("#" + this.playerId);
  },
  watch: {
    playing: function() {
      if (this.playing) {
        this.instance.play();
      } else {
        this.instance.pause();
      }
    }
  },
  methods: {
    togglePlay() {
      this.playing = !this.playing;
    },
    percentChange(currentTime) {
      this.instance.currentTime = currentTime;
      if (!this.playing) {
        this.togglePlay();
      }
    },
    updateTime(e) {
      this.currentTime = e.target.currentTime;
      if (this.instance.ended) {
        this.instance.pause();
      }
    },
    format(interval) {
      interval = interval | 0;
      const minute = (interval / 60) | 0;
      const second = this._pad(interval % 60);
      return `${minute}:${second}`;
    },
    _pad(num, n = 2) {
      let len = num.toString().length;
      while (len < n) {
        num = "0" + num;
        len++;
      }
      return num;
    }
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
@require "../../common/stylus/variable.styl"
.mini-player {
    display: flex
    align-items: center
    left: 0
    bottom: 0
    z-index: 180
    width: 100%
    height: 60px
    border: 1px solid $color-border;

    .icon {
        width: 40px
        padding: 0 10px 0 20px
        display block;
        color $color-warning;

        i {
            display block;
            font-size 40px;

            &.play {
                animation: rotate 10s linear infinite
            }

            &.pause {
                animation-play-state: paused
            }
        }
    }

    .control {
        flex 1;
        padding: 0 10px

        .progress {
            margin 10px 0;
        }
    }
}
</style>
